import 'package:flutter/material.dart';
import 'package:left_scroll_actions/cupertinoLeftScroll.dart';
import 'package:left_scroll_actions/global/actionListener.dart';
import 'package:left_scroll_actions/left_scroll_actions.dart';
import 'package:provider/provider.dart';
import '../../global/Global.dart';
import 'package:useable_app/utils/alert_utils.dart';
import '../../viewmodel/AccountingViewModel.dart';

class AccountingPage extends StatefulWidget {
  const AccountingPage({Key? key}) : super(key: key);

  @override
  _AccountingPageState createState() => _AccountingPageState();
}

class _AccountingPageState extends State<AccountingPage> {
  @override
  void initState() {
    super.initState();
    // loadData();
    if (context.read<AccountingViewModel>().getList.length == 0) loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('记账'),
        centerTitle: true,
        elevation: 10, // 阴影
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(60),
          child: Container(
            padding: EdgeInsets.all(10),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        DateTime.now().year.toString() + "年",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        "本月预算",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        "收入",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        "支出",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        child: Text(
                          Provider.of<AccountingViewModel>(context)
                              .getMonth
                              .toString() +
                              "月",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                          ),
                        ),
                        onTap: _getMonth,
                      ),
                    ),
                    Expanded(
                      child: Text(
                        Global().getInstance().user["money"].toString(),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        Provider.of<AccountingViewModel>(context)
                            .getIncome
                            .toString(),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        Provider.of<AccountingViewModel>(context)
                            .getExpend
                            .toString(),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        actions: [
          IconButton(
            onPressed: () {
              // Navigator.pushNamed(context, "accouting/chart");
            },
            icon: Icon(Icons.chat_rounded),
          ),
        ],
      ),
      body: ListView.builder(
        itemBuilder: _itemBuilder,
        itemCount: Provider.of<AccountingViewModel>(context).getList.length,
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          Navigator.of(context).pushNamed('/accountingAdd');
        },
      ),
    );
  }

  Widget _itemBuilder(BuildContext context, int index) {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.all(10),
          child: Row(
            children: [
              Expanded(
                  child: Text(
                Provider.of<AccountingViewModel>(context).getList[index]
                    ["date"],
                style: Theme.of(context).textTheme.headline6,
              )),
              Text(
                "收入：" +
                    Provider.of<AccountingViewModel>(context)
                        .getList[index]["income"]
                        .toString(),
                style: Theme.of(context).textTheme.bodyText1,
              ),
              SizedBox(
                width: 8,
              ),
              Text(
                "支出：" +
                    Provider.of<AccountingViewModel>(context)
                        .getList[index]["expenditure"]
                        .toString(),
                style: Theme.of(context).textTheme.bodyText1,
              ),
            ],
          ),
        ),
        Divider(height: 1),
        Padding(
            padding: EdgeInsets.fromLTRB(8, 0, 0, 8),
            child: Column(
              children: _chidrens(Provider.of<AccountingViewModel>(context)
                  .getList[index]['data']),
            ))
      ],
    );
  }

  List<Widget> _chidrens(List datas) {
    List<Widget> widgets = [];

    for (var i = 0; i < datas.length; i++) {
      widgets.add(Container(
        height: 8,
      ));
      widgets.add(CupertinoLeftScroll(
        buttons: [
          LeftScrollItem(
            text: '删除',
            color: Colors.red,
            onTap: () {
              context
                  .read<AccountingViewModel>()
                  .delete(datas[i]["id"].toString());
            },
          )
        ],
        key: Key(i.toString()),
        closeTag: LeftScrollCloseTag('LeftScrollCloseTag'),
        child: Row(
          children: [
            Container(
              width: 30,
              height: 30,
              // color: Colors.red,
              child: Icon(
                Icons.event_note_outlined,
                color: Colors.white,
                size: 20,
              ),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15.0),
                  color: Theme.of(context).primaryColor
                )
            ),
            SizedBox(
              width: 16,
            ),
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(datas[i]['type']['action'] == 0 ? '收入' : '支出'),
                Text(
                  "描述：" + datas[i]["desc"],
                  style: TextStyle(
                    color: Colors.grey,
                  ),
                ),
              ],
            )),
            Text(datas[i]["money"].toString()),
            SizedBox(width: 10,)
          ],
        ),
      ));
      // widgets.add(Container(height: 8));
    }

    return widgets;
  }

  void loadData() async {
    // var he = Global().getInstance().dio.options.headers["token"];
    // print(he);
    // context.read<AccountingViewModel>().setList([]);
    context.read<AccountingViewModel>().accountingHistory();
  }

  void _getMonth() async {
    List list = [];
    for (var i = 1; i <= 12; i++) {
      if (i <= DateTime.now().month) list.add(i);
    }
    var result = await showMonthList(list);
    if (result != null) {
      context.read<AccountingViewModel>().setMonth(result);
      loadData();
    }
  }
}
